import 'dart:convert';
import 'dart:math';
import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/guide/sysmodel.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/starRoom/circle_ball.dart';
import 'package:find_friend/pages/starRoom/starspace.dart';
import 'package:find_friend/pages/xspace/post/xpost_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:svgaplayer_flutter/player.dart';

import 'circle_avatar.dart';
import 'model/starmodel.dart';

class StarScreen extends StatefulWidget {

  @override
  _StarScreenState createState() => _StarScreenState();
}

class _StarScreenState extends State<StarScreen> with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin{

  String token = "星域";
  List<HomeRecommdModel> modelList = [];
  List<HomeRecommdModel> randomList = [];
  double scale = 0;
  
  int schoolType = 0;// 所有学校
  int gender = 0;//     男生女生
  bool isfollow = false; // 是否将要关注
  double beginY = 0;
  double endY = 0;
  AnimationController _animationController;
  Animation<Offset> _animation;
  StarspacePage followpage;
  @override
  void initState() {
    super.initState();

    _request();

    _loginRongCloud();
    _initSYSRequest();

    // 动画
    _animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
    CurvedAnimation _curve = CurvedAnimation(parent: _animationController, curve: Curves.easeInOut);
    _animation = Tween<Offset>(begin: Offset(0, 1.0), end: Offset(0, 0)).animate(_curve);
    _animationController.addListener(() { 
      if(_animationController.isCompleted) {
        followpage.refreshData();
      }
    });
    followpage = StarspacePage(onTap: () => _animationController.reverse());
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  // 登录融云
  _loginRongCloud() async {
    try{
      Networktool.request(API.rongtoken, method: NETWORKHTTPMethod.GET, success: (data) {
        if(data != null) {
          RongcloudImPlugin.connect(data["data"]).then((value){
            if(value == 0){
              SharedUserInfo.instance().then((user){
                RongcloudImPlugin.updateCurrentUserInfo(user.mobile, user.nickname, user.avatar);
              });
            } else {
              AlertTool.showToast(value == 0 ? "IM连接成功" : "IM连接失败,退出重试,error:$value");
            }
          });
        }
      });
    } catch(e) {
      AlertTool.showToast(e.toString());
    }
  }

  // 获取用户数据
  _request() {
    Map<String, dynamic> params = {"rows": 20, "gender": gender, "my_school": schoolType};
    // 默认推荐20个人
    Networktool.request(API.recommend, method: NETWORKHTTPMethod.GET, params: params, success: (data){
      if (data['data'] != null) {
        modelList.clear();
        data['data'].forEach((v) {
          HomeRecommdModel m = HomeRecommdModel.fromJson(v);
          modelList.add(m);
        });
        if(scale == 1.0) _randomUser();
      }
    }, fail: (msg) => AlertTool.showToast(msg)
    );
  }

  _requestFollow(HomeRecommdModel model) {
     Networktool.request(API.follow, params: {"mobile": model.mobile}, method: NETWORKHTTPMethod.POST, success: (data){
      AlertTool.showToast("关注成功");
    },
    fail: (msg) => AlertTool.showToast(msg),
    finaly: () => setState(() => isfollow = !isfollow));
  }

  // 初始化系统数据
  _initSYSRequest() {
    Networktool.request(API.sys, method: NETWORKHTTPMethod.GET,success: (data) async {
      if(data != null) {
        SysModel model = data['data'] != null ? SysModel.fromJson(data['data']) : null;
        _saveSys(model);
      }
    });
  }

  _saveSys(SysModel model) {
    Map<String, dynamic> str = model.toJson();
    SharedPreferences.getInstance().then((value) => value.setString(KEY_SYS_Data, json.encode(str)));
  }

  HomeRecommdModel _getRandomModel(List<HomeRecommdModel> list) {
    if(list.length == 0) return null;
    int index = Random().nextInt(list.length - 1);
    return list[index];
  }

  void _randomUser() {
    if(scale == 1 && randomList.isEmpty){
      // 更新用户选择数据
      randomList.clear();
      List<HomeRecommdModel> arr = [];
      List<HomeRecommdModel> tempRandom = modelList.map((e) => e).toList();
      List.generate(9, (index) {
        HomeRecommdModel model = _getRandomModel(tempRandom);
        arr.add(model);
        tempRandom.remove(model);
      });
      randomList = arr;
    }
    if(scale == 0) {
      randomList.clear();
    }
    setState(() {
      
    });
  }

  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;
    final padding = MediaQuery.of(context).padding;
    return Scaffold(
      body: GestureDetector(
        onVerticalDragStart: (details) => beginY = details.globalPosition.dy,
        onVerticalDragUpdate: (details) => endY = details.globalPosition.dy,
        onTap: () {
          scale = 1; // 点击显示头像
          _randomUser();
        },
        onVerticalDragEnd: (details) {
          if(beginY - endY > 10) {
            _animationController.forward();
          }
        },
        onScaleUpdate: (details){
          double temp = details.scale + scale - 1;
          if(temp > 1) temp = 1;
          if(temp < 0) temp = 0;
          scale = temp;
          _randomUser();
        },
        child: Stack(
          children: [
            Container(
              width: size.width,
              height: size.height,
              color: Colors.black,
              child: SVGASimpleImage(assetsName: "assets/gif/star.svga",)
            ),
            Container(
              width: size.width,
              height: size.height,
              child: Image.asset("assets/star_bg.png", fit: BoxFit.cover,)
            ),
            Container(
              width: size.width,
              height: size.height - 50,
              child: SVGASimpleImage(assetsName: "assets/gif/round_ball.svga",)
            ),
            Center(
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 50),
                margin: const EdgeInsets.only(bottom: 30, left: 20),
                child: Image.asset("assets/ball_line.png", fit: BoxFit.fitWidth,)
              ),
            ),
            Center(
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 50),
                margin: const EdgeInsets.only(bottom: 25, left: 20),
                child: Image.asset("assets/ball_line2.png", fit: BoxFit.fitWidth,)
              ),
            ),
            Offstage(
              offstage: scale == 1,
              child: CircleBallWidget(),
            ),
            

            // 标题
            Positioned(
              top: padding.top,
              left: 0,
              right: 0,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Column(
                    children: [
                      Text("FIND", style: TextStyle(fontFamily: "cabin", fontSize: 17, color: Colors.white),),
                      Text("You are not alone", style: TextStyle(fontFamily: "snell", fontSize: 14, color: Colors.white),),
                    ],
                  )
                ],
              ),
            ),

            // 筛选
            Positioned(
              top: 45 + padding.top,
              left: 15,
              right: 0,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _HomeFliterWidget(title: "ALL", tag: schoolType,list: ["ALL", '本校','非本校'],onTap: (tag){
                        setState(() {
                          schoolType = tag;
                        });
                        _request();
                      },),
                      _HomeFliterWidget(title: "不限", tag: gender,list: ["不限", 'BOY','GIRL'], onTap: (tag){
                        setState(() {
                          gender = tag;
                        });
                        _request();
                      },)
                    ],
                  ),
                  Image.asset("assets/beike2.png")
                ],
              ),
            ),

            // 一键分享
            Positioned(
              left: 15,
              right: 15,
              bottom: padding.bottom,
              child: Offstage(
                offstage: scale == 1,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Image.asset("assets/yijian.png"),
                    Image.asset("assets/taiyan.png")
                  ],
                ),
              ),
            ),

            // 一键分享
            Positioned(
              bottom: padding.bottom,
              child: DragTarget<HomeRecommdModel>(
                onWillAccept: (data){
                  setState(() {
                    isfollow = true;
                  });
                  return true;
                },
                onLeave: (data) => setState(()=> isfollow = false),
                onAccept: _requestFollow,
                builder: (context, candidateData, rejectedData) {
                  return Container(
                    width: size.width,
                    height: 60,
                    alignment: Alignment.center,
                    child: InkWell(
                      onTap: (){
                        _animationController.forward();
                      },
                      child: Image.asset("assets/shanghua2.png", height: 60, width: 60, color: isfollow ? APP_main_color : Colors.white,),
                    ),
                  );
                }
              ),
            ),
            Positioned.fill(
              bottom: 70 + padding.bottom / 2,
              top: 150,
              child: Container(
                child: Offstage(
                  offstage: scale != 1,
                  child: Opacity(
                    opacity: scale,
                    child: CircleHeadWidget(list: randomList, onHidden: (){
                      setState(() {
                        scale = 0;
                      });
                    },),
                  ),
                ),
              ),
            ),
            Positioned.fill(
              child: SlideTransition(
                position: _animation,
                child: followpage,
              ),
            ),

            // 搜索
            Positioned(
              right: 10,
              top: padding.top,
              child: Row(
                children: [
                  InkWell(
                    onTap: () => Navigator.pushNamed(context, '/search'),
                    child: Image.asset("assets/sousuo.png", width: 30,color: Colors.white,)
                  ),
                  GestureDetector(
                    onTap: () {
                      push(context, XPostPage());
                    },
                    child: Image.asset("assets/fabu2.png", width: 30,color: Colors.white,),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

// 筛选
class _HomeFliterWidget extends StatefulWidget {

  String title;
  final int tag;
  final List<String> list;
  final Function(int tag) onTap;

  _HomeFliterWidget({Key key, this.tag, this.title, this.list, this.onTap}) : super(key: key);

  @override
  __HomeFliterWidgetState createState() => __HomeFliterWidgetState();
}

class __HomeFliterWidgetState extends State<_HomeFliterWidget> with SingleTickerProviderStateMixin{

  AnimationController _controller;
  Animation<double> _animation;
  int index = 0;
  static const List<String> englishes = ["ALL", "BOY", "GIRL"];
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    CurvedAnimation _curve = CurvedAnimation(curve: Curves.easeIn, parent: _controller);
    _animation = Tween<double>(begin: 0, end: 1).animate(_curve);

    _controller.addListener(() { 
      setState(() {
        
      });
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Widget _createText(int idx, String title) {
    TextStyle textStyle;
    if(englishes.contains(title)) {
      textStyle = TextStyle(fontSize: 15.sp, fontStyle: FontStyle.italic, fontFamily: "cabin", color: index == idx ? APP_main_color : Colors.white);
    } else {
      textStyle = TextStyle(fontSize: 15.sp, fontStyle: FontStyle.normal, color: index == idx ? APP_main_color : Colors.white);
    }
    return InkWell(
      onTap: (){
        setState(() {
          index = idx;
          widget.title = title;
        });
        if(widget.onTap != null) widget.onTap(idx);
        _controller.reverse();
      },
      child: Text(title, style: textStyle,)
    );
  }

  TextStyle _getEnglishStyle() {
    return englishes.contains(widget.list[widget.tag]) ? TextStyle(fontSize: 15.sp, fontStyle: FontStyle.italic, fontFamily: "cabin", color: APP_main_color) :
      TextStyle(fontSize: 15.sp, fontStyle: FontStyle.normal, color: APP_main_color);
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Row(
            children: [
              InkWell(
                onTap: (){
                  if(_controller.isCompleted) {
                    _controller.reverse();
                  } else {
                    _controller.forward();
                  }
                },
                child: Container(
                  width: 60.w,
                  height: 40,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage("assets/buxian22.png"),
                      fit: BoxFit.fitWidth
                    )
                  ),
                  child: Text(widget.list[widget.tag], style: _getEnglishStyle(),),
                ),
              ),
              Transform(
                transform: Matrix4.identity()..scale(_animation.value),
                origin: Offset(0, 20),
                child: Container(
                  width: size.width * 0.45,
                  height: 40,
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage("assets/xuanze22.png"),
                      fit: BoxFit.fitWidth
                    )
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: widget.list.map((e) => 
                      _createText(widget.list.indexOf(e), e)
                    ).toList(),
                  ),
                ),
              ),
            ],
          );
  }
}